package com.bac.rentmap.ad.flat.crawler.blingby;

import java.io.IOException;
import java.util.List;
import java.util.logging.Logger;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.springframework.beans.factory.annotation.Required;
import org.xml.sax.SAXException;

import com.bac.rentmap.ad.crawler.AdCrawler;
import com.bac.rentmap.ad.crawler.Context;
import com.bac.rentmap.ad.flat.crawler.FlatCrawledAd;
import com.bac.rentmap.ad.flat.crawler.localaddress.LocalAddressParser;

public class BlingByAdCrawler implements AdCrawler<FlatCrawledAd> {
    private static final Logger log = Logger.getLogger(BlingByAdCrawler.class
            .getName());
    
    public static final String SOURCE_URL = "http://bling.by";
    private static final String WS_URL = SOURCE_URL + "/offers.yrl";
    private LocalAddressParser localAddressParser;

    @Override
    public List<FlatCrawledAd> crawl(Context context) throws IOException {
        try {
            SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser();
            BlingBySaxHandler saxHandler = new BlingBySaxHandler(localAddressParser);
            log.fine("Connecting to " + WS_URL);
            saxParser.parse(WS_URL, saxHandler);
            List<FlatCrawledAd> res = saxHandler.getRes();
            log.fine("Crawled " + res.size() + " FlatCrawledAds");
            return res;
        } catch (ParserConfigurationException e) {
            throw new RuntimeException("Failed to create SAX parser to parse blingby", e);
        } catch (SAXException e) {
            throw new RuntimeException("Failed to parse blingby", e);
        }
    }

    @Required
    public void setLocalAddressParser(LocalAddressParser localAddressParser) {
        this.localAddressParser = localAddressParser;
    }
}
